<style lang="scss">
  .tagTitle{
    background-color: #e6f0fd;
    border-color: #cce1fa;
    color: #0067e7;
    display: inline-block;
    height: 23px;
    margin-left: 10px;
    padding: 0 5px;
    font-size: 12px;
    color: #0067E7;
    border-width: 1px;
    border-style: solid;
    border-radius: 4px;
    box-sizing: border-box;
    white-space: nowrap;
  }
</style>
<style lang="scss">
  @import "./setEntry.scss";
</style>
	<style  lang="scss">
div#rMenu {position:absolute; visibility:hidden; top:0;text-align: left;padding: 2px;}
div#rMenu ul{
  margin: 0;
  padding: 0;
  li{
    margin: 1px 0;
    padding: 0 5px;
    cursor: pointer;
    list-style: none outside none;
    background-color: #DFDFDF;
  }
}
 
    
	</style>
<template>
  <div style="height:100%">
    <el-container style="height:100%;border: 1px solid #eee">
      <el-aside width="30%" style="background-color: rgb(238, 241, 246)">
        <el-row :span="24" :gutter="20">
          <el-col :span="24">
            <el-input placeholder="请输入内容" id="key" v-model="form"><template slot="append"><el-button slot="append" icon="el-icon-search"></el-button></template></el-input>
          </el-col>
          <el-col :span="24">
            <el-button type="text" icon="el-icon-full-screen" @click="expandAll()">{{expandAllState?'收缩全部':'展开全部'}}</el-button>
            <el-button type="text" icon="el-icon-coin" @click="checkAll()">{{checkAllState?'反选':'全选'}}</el-button>
            <el-button type="text" icon="el-icon-check" @click="addEntry()">新增条目</el-button>
            <el-button type="text" icon="el-icon-close" @click="cancleEntry()">取消条目</el-button>
            <el-button type="text" icon="el-icon-setting">已有条目({{entryCount}})</el-button>
            <!-- <el-button type="text" icon="el-icon-document-copy">合计条目</el-button> -->
          </el-col>
        </el-row>
        <div class='zTreeDemoBackground left'>
            <ul id='treeDemo' class='ztree'></ul>
            <div id="rMenu">
              <ul>
                <li id="m_add" @click="editEntryCont();">编辑内容</li>
                <li id="m_del" @click="removeTreeNode();">测试1</li>
                <li id="m_check" @click="checkTreeNode(true);">测试2</li>
                <li id="m_unCheck" @click="checkTreeNode(false);">测试3</li>
                <li id="m_reset" @click="resetTree();">测试4</li>
              </ul>
            </div>
        </div>
      </el-aside>
      <el-container class="set-entry-cont">
        <el-main id="word-main" style="position: relative;">
          <div v-show='!isEdit' v-html="wordHtml" class='word-main-html'></div>
          <div id="editorElem-cont" v-show='isEdit' style="margin-left: 10%;padding: 30px;width: 80%;position: absolute;">
            <div id="editorElem"></div>
          </div>
        </el-main>
      </el-container>
    </el-container>
    





    
    


  </div>
</template>

<script>
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {analysisWord} from '@/api/biz/demand/bizDemandEntryApi';
export default {
  props:['url'],
  data() {
    return {
      form:'',
      option: {
        labelWidth: 120,
        column: [
          {
            label: '搜索内容',
            prop: 'search',
            type: 'search',
            appendClick:()=>{
              this.$message.success('搜索回调'+this.form.search);
            }
          }
        ]
      },
      setting:{
        view: {
          nameIsHTML: true,
          // addHoverDom: this.addHoverDom,
          // removeHoverDom: this.removeHoverDom,
          selectedMulti: false
        },
        check: {
          enable: true
        },
        data: {
          simpleData: {
            enable: true
          }
        },
        // edit: {
        //   enable: true
        // },
        callback: {
          beforeClick: this.zTreeBeforeClick,
          onRightClick: this.OnRightClick,
        },
        
      },
      zNodes:[],
      newCount:1,
      ztree:'',
      // 全选状态
      checkAllState:false,
      // 展开状态
      expandAllState:false,
      // 条目总数
      entryCount:0,
      // html代码
      wordHtml:'',
      // 右侧小菜单
      rMenu:'',
      // 是否编辑富文本
      isEdit:false,
      // 富文本编辑器
      editor:null
    };
  },
  computed: {
    ...mapGetters(['website','orgTree','genOrgTree','userInfo','permission','projectInfo']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.general_staff_station_add, false),
        viewBtn: this.vaildData(this.permission.general_staff_station_view, false),
        delBtn: this.vaildData(this.permission.general_staff_station_delete, false),
        editBtn: this.vaildData(this.permission.general_staff_station_edit, false),
        printBtn: this.vaildData(this.permission.general_staff_station_print, false),
        searchBtn:this.vaildData(this.permission.general_staff_station_search, false)
      };
    },
  },
  methods: {
    /**
     * 加载列表数据
     */
    onLoad() {
      analysisWord({filePath:this.url,tenantId:'DOOL1001'}).then(res => {
        this.wordHtml = res.data.htmlBody;
        this.zNodes = res.data.directories;
        this.changeNodesName();
        // 加载树形结构
        $.fn.zTree.init($('#treeDemo'), this.setting,this.zNodes);
        fuzzySearch('treeDemo','#key',null,true);
        this.ztree = $.fn.zTree.getZTreeObj('treeDemo');
        this.rMenu = $('#rMenu');
      }, error => {
        
      });
    },
    // 新增节点
    addHoverDom(treeId, treeNode) {
      var sObj = $('#' + treeNode.tId + '_span');
      if (treeNode.editNameFlag || $('#addBtn_'+treeNode.tId).length>0) return;
      var addStr = '<span class="button add" id="addBtn_' + treeNode.tId + '" title="add node" onfocus="this.blur();"></span>';
      sObj.after(addStr);
      var btn = $('#addBtn_'+treeNode.tId);
      if (btn) btn.bind('click', function(){
        var zTree = $.fn.zTree.getZTreeObj('treeDemo');
        zTree.addNodes(treeNode, {id:(100 + this.newCount), pId:treeNode.id, name:'new node' + (this.newCount++)});
        return false;
      });
    },
    // 删除节点
    removeHoverDom(treeId, treeNode) {
      $('#addBtn_'+treeNode.tId).unbind().remove();
    },
    // 全选/反选
    checkAll(){
      this.checkAllState = !this.checkAllState;
      this.ztree.checkAllNodes(this.checkAllState);
    },
    // 展开/收缩
    expandAll(){
      this.expandAllState = !this.expandAllState;
      this.ztree.expandAll(this.expandAllState);
    },
    // 新增条目
    addEntry(){
      var	nodes = this.ztree.getSelectedNodes();
      if(nodes.length == 0){
        this.$message({showClose: true,message: '请先选择一个节点',type: 'warning'});
        return;
      }
      if(nodes[0].isParent){
        this.$message({showClose: true,message: '只有最低级才可添加条目',type: 'warning'});
        return;
      }
      if(nodes[0].label === '1'){
        this.$message({showClose: true,message: '该节点已经是条目',type: 'warning'});
        return;
      }
      let changeNode = this.changeNodesName('add',nodes[0].id);
      nodes[0].name = changeNode.name;
      nodes[0].label = changeNode.label;
      this.ztree.updateNode(nodes[0]);
    },
    // 条目变化
    changeNodesName(type,id){
      this.entryCount = 0;
      let backNode = {};
      let tagHtml = '<span class="tagTitle">条目</span>';
      this.zNodes.forEach(item=>{
        if(item.isParent){
          item.noR = true;
        }
        if(type === 'add'){
          if(item.id == id){
            item.name = item.name.replace(/_[\d]*$/g, '') + tagHtml;
            item.label = '1';
            backNode = item;
          }
        }else if(type === 'cancle'){
          if(item.id == id){
            item.name = item.name.replace(new RegExp(tagHtml,'g'), '');
            item.label = '';
            backNode = item;
          }
        }else{
          item.name = item.label === '1'?(item.name.replace(/_[\d]*$/g, '') + tagHtml) : (item.name.replace(new RegExp(tagHtml,'g'), ''));
        }
        this.entryCount = this.entryCount + (item.label === '1'?1:0);
      });
      if(type){
        return backNode;
      }
    },
    // 取消条目
    cancleEntry(){
      var	nodes = this.ztree.getSelectedNodes();
      if(nodes.length == 0){
        this.$message({showClose: true,message: '请先选择一个节点',type: 'warning'});
        return;
      }
      if(nodes[0].label !== '1'){
        this.$message({showClose: true,message: '该节点不是条目',type: 'warning'});
        return;
      }
      let changeNode = this.changeNodesName('cancle',nodes[0].id);
      nodes[0].name = changeNode.name;
      nodes[0].label = changeNode.label;
      this.ztree.updateNode(nodes[0]);
    },
    // 锁定文档具体位置
    zTreeBeforeClick(treeId, treeNode, clickFlag){
      let top = $('#position'+treeNode.id)[0].offsetTop - 75;
      $('#word-main').animate({scrollTop: top }, {duration: 500,easing: 'swing'});
    },
    OnRightClick(event, treeId, treeNode) {
      if (!treeNode && event.target.tagName.toLowerCase() != 'button' && $(event.target).parents('a').length == 0) {
        this.ztree.cancelSelectedNode();
        this.showRMenu('root', event.clientX, event.clientY,event);
      } else if (treeNode && !treeNode.noR) {
        this.ztree.selectNode(treeNode);
        this.showRMenu('node', event.clientX, event.clientY,event);
      }
    },
    showRMenu(type, x, y,event) {
      $('#rMenu ul').show();
      if (type=='root') {
        $('#m_del').hide();
        $('#m_check').hide();
        $('#m_unCheck').hide();
      } else {
        $('#m_del').show();
        $('#m_check').show();
        $('#m_unCheck').show();
      }
      y += document.body.scrollTop;
      x += document.body.scrollLeft; 
      $('#rMenu').css({'top':y+'px','left':x+'px','visibility':'visible'});
      $('body').bind('mousedown',this.onBodyMouseDown);
    },
    hideRMenu() {
      if (this.rMenu) this.rMenu.css({'visibility': 'hidden'});
      let onBodyMouseDown = (event)=>{
        if (!(event.target.id == 'rMenu' || $(event.target).parents('#rMenu').length>0)) {
          this.rMenu.css({'visibility' : 'hidden'});
        }
      }
      $('body').unbind('mousedown',this.onBodyMouseDown);
    },
    onBodyMouseDown(event){
      if (!(event.target.id == 'rMenu' || $(event.target).parents('#rMenu').length>0)) {
        this.rMenu.css({'visibility' : 'hidden'});
      }
    },
    editEntryCont(){
      var node = this.ztree.getSelectedNodes();
      let before = $('#position'+ node[0].id)[0].outerHTML;
      let after = '';
      this.zNodes.forEach((item,index)=>{
        if(item.id == node[0].id){
          // this.editor.txt.html('<p>用 JS 设置的内容12313</p>');
          //this.$console.log(item.content);
          this.editor.txt.html(item.content);
        }
      });
      this.hideRMenu();
      this.isEdit = true;
      // this.zTreeBeforeClick(null, node[0], null);
      // let top = $('#position'+node[0].id)[0].offsetTop + $('#position'+node[0].id)[0].offsetHeight - 25;
      // $('#editorElem-cont').css('top',top);
    }, 
    // 保存后修改html
    editHtml(){
      this.isEdit = false;
      this.editor.txt.clear();
      var node = this.ztree.getSelectedNodes();
      //this.$console.log(node[0]);
      this.zTreeBeforeClick(null, node[0], null);
    }, 
  },
  mounted() {
    this.onLoad();
    const E = window.wangEditor;
    let self = this;
    this.editor = new E('#editorElem');

    let { $, BtnMenu } = E;
    class AlertMenu extends BtnMenu {
      constructor(editor) {
        const $elem = E.$('<div class="w-e-menu">保存</div>');
        super($elem, editor)
      }
      clickHandler() {
        self.editHtml();
      }
      tryChangeActive() {
        // this.active()
      }
    }
    this.editor.menus.extend('close', AlertMenu)

    this.editor.config.menus = [
      'head', // 标题  
      'bold', // 粗体  
      'fontSize', // 字号  
      'fontName', // 字体  
      'italic', // 斜体  
      'underline', // 下划线  
      'link', // 插入链接  
      'list', // 列表  
      'justify', // 对齐方式  
      'quote', // 引用  
      'image', // 插入图片  
      'table', // 表格   
      'undo', // 撤销  
      'redo', // 重复  
      'fullscreen', // 全屏 
    ];
    // 将菜单加入到 editor.config.menus 中
    // 也可以通过配置 menus 调整菜单的顺序，参考【配置菜单】部分的文档
    this.editor.config.menus = this.editor.config.menus.concat('close')

    this.editor.create();
    

  },
  beforeDestroy() {
    // 销毁编辑器
    this.editor.destroy();
    this.editor = null
  }
};
</script>
